/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trocabi.view;

import trocabi.Socle.TechnicalException;
import java.awt.BorderLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

public class WaitingFrame extends JFrame {
    public WaitingFrame(String title) {
        final JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);
        final JPanel contentPane = new JPanel();
        contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        contentPane.setLayout(new BorderLayout());
        contentPane.add(new JLabel(title), BorderLayout.NORTH);
        contentPane.add(progressBar, BorderLayout.CENTER);
        setContentPane(contentPane);
        pack();
        setLocationRelativeTo(null);
    }

    public void setTask(Runnable taskDef) {
        task = new Thread(taskDef);
    }

    public void start() throws TechnicalException {
        if (task == null) {
            throw new TechnicalException("La tache n'est pas definie");
        }
        setVisible(true);
        task.start();
    }

    public void waitEnd() {
        if (task == null) {
            return;
        }
        try {
            task.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(WaitingFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        setVisible(false);
    }
    private Thread task = null;

    public static void example() throws Throwable {
        Runnable myTask = new Runnable() {
            public void run() {
                System.out.println("Starting task");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(WaitingFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println("End task");
            }
        };
        System.out.println("debut");
        WaitingFrame waitMe = new WaitingFrame("Waiting...");
        waitMe.setTask(myTask);
        waitMe.start();
        waitMe.waitEnd();
        System.out.println("ici");
        Thread.sleep(2000);
        System.out.println("fin");
    }
}

